package com.ego.dubbo.service.impl;

import com.ego.commons.exception.DaoException;
import com.ego.commons.pojo.EgoResult;
import com.ego.dubbo.service.TbUserDubboService;
import com.ego.mapper.TbUserMapper;
import com.ego.pojo.TbUser;
import com.ego.pojo.TbUserExample;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Title
 * @Author Lyg
 * @Description:
 */
@DubboService
public class TbUserDubboServiceImpl implements TbUserDubboService {


    @Autowired
    private TbUserMapper tbUserMapper;
    @Override
    public TbUser selectByUser(TbUser user) {
        TbUserExample tbUserExample = new TbUserExample();

        if (StringUtils.isNotBlank(user.getUsername())){
            tbUserExample.createCriteria().andUsernameEqualTo(user.getUsername());
        }else if(StringUtils.isNotBlank(user.getEmail())){
            tbUserExample.createCriteria().andEmailEqualTo(user.getEmail());
        }else if (StringUtils.isNotBlank(user.getPhone())){
            tbUserExample.createCriteria().andPhoneEqualTo(user.getPhone());
        }
        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);

        return tbUsers.size()==1?tbUsers.get(0):null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertTbUser(TbUser user) throws DaoException {
        try {
            return tbUserMapper.insertSelective(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new  DaoException("新增用户失败");
        }
    }

    @Override
    public TbUser login(TbUser tbUser) {
        TbUserExample tbUserExample = new TbUserExample();
        tbUserExample.createCriteria().andUsernameEqualTo(tbUser.getUsername()).andPasswordEqualTo(tbUser.getPassword());

        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);
        return tbUsers.size()==1?tbUsers.get(0):null;
    }
}
